﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework;

namespace Z2.Core
{
	public class SoundManager
	{

		#region Members

		private bool m_noAudio;
		private static volatile SoundManager _instance;
		private static object _syncRoot = new object();
		private Random m_rnd = new Random();

		private ContentManager m_contentManager;
		private readonly Dictionary<string, SoundEffect> m_sounds;

		#endregion

		#region Constructor

		protected SoundManager()
		{
			this.m_sounds = new Dictionary<string,SoundEffect>();
		}

		#endregion 

		#region Methods

		public void PlayDistance(SoundEffect effect, ObjectBase obj)
		{
			if(effect == null) return;
			var ppos = World.Current.Player.Position;
			float pitch = 0.0f + (this.m_rnd.Next(-20, 20) / 100.0f);
			Vector2 result = Vector2.Subtract(ppos, obj.Position);
			var pan = (1.0f / 512.0f) * (obj.Position.X - ppos.X);
			float l = Math.Abs(result.Length());
			float max = 1.0f - ((1.0f / 512.0f) * l);
			max = max > 1 ? 1 : max;
			if (max < 0 || Math.Abs(pan) > 1) return;
			effect.Play(max, pitch, pan);
		}

		public SoundEffect LoadSound(string alias)
		{
			if (this.m_noAudio) return null;
			if (this.m_sounds.ContainsKey(alias))
				return this.m_sounds[alias];

			SoundEffect effect = null;
			try
			{
				effect = this.m_contentManager.Load<SoundEffect>("Sounds/" + alias);
			}
			catch (NoAudioHardwareException)
			{
				this.m_noAudio = true;
			}
			
			this.m_sounds.Add(alias, effect);

			return effect;
		}

		public void Initialize(ContentManager content)
		{
			this.m_contentManager = content;
		}

		#endregion

		#region Properties

		public static SoundManager Instance
		{
			get
			{
				if (_instance == null)
				{
					lock (_syncRoot)
					{
						if (_instance == null)
							_instance = new SoundManager();
					}
				}
				return _instance;
			}
		}

		#endregion

	}
}
